<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="设备" prop="equipment">
        <el-select v-model="queryParams.equipment" placeholder="请选择设备" clearable filterable size="small">
          <el-option v-for="item in shebeiOptions" :key="item.bookId" :label="item.bookName" :value="item.bookId" />
        </el-select>
      </el-form-item>
      <el-form-item label="设备类型" prop="equipmentType">
        <treeselect v-model="queryParams.equipmentType" :options="equipmentTypeOption" :normalizer="normalizerazSblx"
          style="width: 240px" placeholder="请选择设备类型" />
      </el-form-item>
      <el-form-item label="项目名称" prop="itemName">
        <el-input v-model="queryParams.itemName" placeholder="请输入项目名称" clearable size="small" style="width: 200px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['equipment:inspectProject:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['equipment:maintain:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['equipment:maintain:remove']">删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['equipment:maintain:export']">导出</el-button>
      </el-col> -->
      <!--  -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="ServiceList" @selection-change="handleSelectionChange" style="width: 100%">
      <el-table-column type="selection" width="60" align="center" fixed="left" />
      <el-table-column label="设备" align="center" prop="equipment" width="300" fixed="left"
        :formatter="equipmentFormatter" />
      <el-table-column label="设备类型" align="center" prop="equipmentType" width="300"
        :formatter="equipmentTypeFormatter" />
      <!-- <el-table-column label="点检类型" align="center" prop="byLx" width="200">
        <template slot-scope="scope">
          <span>{{scope.row.byLx===1?'点检':scope.row.byLx===2?'点检':''}}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="是否启用" align="center" prop="ifOpen" width="100">
        <template slot-scope="scope">
          <span>{{['否','是'][scope.row.ifOpen]}}</span>
        </template>
      </el-table-column>
      <el-table-column label="项目编码" align="center" prop="itemCode" width="150" />
      <el-table-column label="项目名称" align="center" prop="itemName" width="150" />
      <el-table-column label="点检明细" align="center" prop="keepDetailed" width="200" />

      <el-table-column label="点检周期cron表达式" align="center" prop="keepPeriod" width="200" />
      <el-table-column label="预计工时" align="center" prop="workingHours" width="100" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" style="margin-right: 9px"
            @click="handleUpdate(scope.row)" v-hasPermi="['equipment:inspectProject:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['equipment:inspectProject:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改设备点检对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="760px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="24">
          <el-col :span="16">
            <el-form-item label="设备" prop="equipment">
              <el-select multiple v-model="form.equipment" placeholder="请选择设备" clearable size="small">
                <el-option v-for="item in shebeiOptions" :key="item.bookId" :label="item.bookName"
                  :value="item.bookId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="设备类型" prop="equipmentType">
              <treeselect multiple v-model="form.equipmentType" :options="equipmentTypeOption"
                :normalizer="normalizerazSblx" style="width: 240px" placeholder="请选择设备类型" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="项目编码" prop="itemCode">
              <el-input v-model="form.itemCode" placeholder="请输入项目编码" style="width: 240px" />
            </el-form-item>
          </el-col>
          <el-col :lg="12">

            </el-form-item>
            <el-form-item label="项目名称" prop="itemName">
              <el-input v-model="form.itemName" placeholder="请输入项目名称" style="width: 240px" />
            </el-form-item>
          </el-col>
          <el-col :lg="12">
            <el-form-item label="点检内容" prop="keepDetailed">
              <el-input v-model="form.keepDetailed" placeholder="请输入点检内容" style="width: 240px" />
            </el-form-item>
          </el-col>
          <el-col :lg="12">
            <el-form-item label="预计工时" prop="workingHours">
              <el-input v-model="form.workingHours" placeholder="请输入预计工时" style="width: 240px" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="是否启用" prop="ifOpen">
              <el-radio-group v-model="form.ifOpen" size="small">
                <el-radio-button :label="0">否</el-radio-button>
                <el-radio-button :label="1">是</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="16">
            <el-form-item label="点检周期" prop="keepPeriod">
              <el-input v-model="form.keepPeriod" placeholder="请输入cron执行表达式">
                <template slot="append">
                  <el-button type="success" @click="handleShowCron">
                    生成表达式
                    <i class="el-icon-time el-icon--right"></i>
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="Cron表达式生成器" :visible.sync="openCron" append-to-body destroy-on-close class="scrollbar">
      <crontab @hide="openCron=false" @fill="crontabFill" :expression="expression"></crontab>
    </el-dialog>

  </div>
</template>

<script>
  import {
    listService,
    getService,
    delService,
    addService,
    updateService,
  } from "@/api/equipment/maintainProject";
  import { listBill } from "@/api/equipment/bill";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import Crontab from '@/components/Crontab'
  import { listEquipmentType } from "@/api/equipment/type";

  export default {
    name: "MaintainProject",
    components: { Crontab, Treeselect },
    data() {
      return {
        // 遮罩层
        loading: true, openCron: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 点检项目表格数据
        ServiceList: [], expression: '', openCron: false, shebeiOptions: [], equipmentTypeOption: [], equipmentTypeNames: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          byLx: 2
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          orderCode: [{ required: true, message: "工单编码不能为空", trigger: "change" }],
          materialCode: [{ required: true, message: "物料编码不能为空", trigger: "change" }]
        }
      };
    },
    created() {
      this.getList();
      /* 设备类型树选择 */
      listEquipmentType().then(res => {
        this.equipmentTypeOption = res.data
      })
      /* 设备下拉选择 */
      listBill().then((response) => {
        this.shebeiOptions = response.rows;
      });
    },
    methods: {
      /** 查询点检项目列表 */
      getList() {
        this.loading = true;
        listService(this.queryParams).then(response => {
          this.ServiceList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      /* 设备类型格式化 */
      equipmentTypeFormatter(row) {
        return this.getName(row.equipmentType, this.equipmentTypeOption)
      },
      /* 树节点是否存在该id */
      isNodeId(id, arr) {
        for (var i in arr) {
          if (arr[i] == id) {
            return true
          }
        }
      },
      /* 通过id查找设备类型树对应的名字 */
      getName(arr, data) {
        var newArr = []
        for (var j in data) {
          if (this.isNodeId(data[j].typeId, arr)) {
            newArr.push(data[j].typeName)
          }
          if (data[j].children?.length > 0) {
            this.getName(arr, data[j].children, newArr)
          }
        }
        this.equipmentTypeNames = newArr
        return newArr.join('、')
      },
      /* 设备格式化 */
      equipmentFormatter(row) {
        var arr = []
        this.shebeiOptions.map((item, index) => {
          row.equipment.map(it => {
            if (item.bookId === it) {
              arr.push(item.bookName)
            }
          })
        })
        return arr.join('、')
      },
      /* 设备类型转换结构 */
      normalizerazSblx(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.typeId,
          label: node.typeName,
          children: node.children
        };
      },
      /** cron表达式按钮操作 */
      handleShowCron() {
        this.expression = this.form.keepPeriod;
        this.openCron = true;
      },
      /** 确定后回传值 */
      crontabFill(value) {
        this.form.keepPeriod = value;
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {};
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.byId);
        this.single = selection.length !== 1;
        this.multiple = !selection.length;
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加点检项目";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const byIds = row.byId || this.ids;
        getService(byIds).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改点检项目";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.title === '修改点检项目') {
              updateService({ ...this.form, byLx: 2 }).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                }
              });
            } else {
              addService({ ...this.form, byLx: 2 }).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                }
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const byIds = row.byId || this.ids;
        this.$confirm('是否确认删除点检项目编号id为"' + byIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          delService(byIds).then(() => {
            this.getList();
            this.msgSuccess("删除成功");
          }).catch(function () { });;
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有点检项目数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return exportOrder(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function () { });
      }
    }
  };
</script>